#include "wav.h"
#include<cstdio>
#include <iostream>
#include <cstring>
Wav::Wav()
{
	memset(&header,0,sizeof header);
}
WavHeader Wav::getHeader()
{
	return header;
}
void Wav::setHeader(WavHeader newHeader)
{
	header = newHeader;
}
unsigned char* Wav::getData()
{
	return data;
}
void Wav::setData(unsigned char* newData)
{
	data = newData;
}
void Wav::setLength(long len)
{
	length = len;
}
long Wav::getLength()
{
	return length;
}
void Wav::readWav(char* fileName)
{
	try
	{
		FILE *f_in;
		if((f_in = fopen(fileName,"r+b")) == NULL) throw 1;

		if ((fread(&header,sizeof header,1,f_in)) == NULL) throw 2 ;
		data = new unsigned char[header.chunkSize];
		if (header.bitsPerSample != 8 )
		{
			std::cout<<"wrong bitsPerSample parameter\n";
		}
		if(header.subchunk1Size != 16)
		{
			std::cout<<"warning! compressed data, compression ignored\n";
			header.subchunk1Size = 16;
			header.subchunk2Id[0] = 'd';
			header.subchunk2Id[1] = 'a';
			header.subchunk2Id[2] = 't';
			header.subchunk2Id[3] = 'a';
		}
		for(length =0; fread(&data[length],sizeof(unsigned char),1,f_in); length ++);
		length++;
		header.subchunk2Size = length;
		fclose(f_in);
	}
	catch(...)
	{
		std::cout<<"reading failed\n";
	}
}
void Wav::writeWav(char* fileName)
{
	try
	{
		FILE *f_out;
		if((f_out = fopen(fileName,"w+b")) == NULL) throw 1;
		if((fwrite(&header,sizeof header,1,f_out))== NULL) throw 1;
		for(int i = 0; i < length; i++)
		{
			if((fwrite(&data[i],sizeof(unsigned char),1,f_out))== NULL);
		}
		fclose(f_out);
	}
	catch(...)
	{
		std::cout<<"writing failed\n";
	}
}
void Wav::toConsole()
{
	std::cout<<"chunkId        "<<header.chunkId <<std::endl;
	std::cout<<"chunkSize      "<<header.chunkSize <<std::endl;
	std::cout<<"format         "<<header.format <<std::endl;
	std::cout<<"subchunk1Id    "<<header.subchunk1Id <<std::endl;
	std::cout<<"subchunk1Size  "<<header.subchunk1Size <<std::endl;
	std::cout<<"audioFormat    "<<header.audioFormat <<std::endl;
	std::cout<<"numChannels    "<<header.numChannels <<std::endl;
	std::cout<<"sampleRate     "<<header.sampleRate <<std::endl;
	std::cout<<"byteRate       "<<header.byteRate <<std::endl;
	std::cout<<"blockAlign     "<<header.blockAlign <<std::endl;
	std::cout<<"bitsPerSample  "<<header.bitsPerSample <<std::endl;
	std::cout<<"subchunk2Id    "<<header.subchunk2Id <<std::endl;
	std::cout<<"subchunk2Size  "<<header.subchunk2Size <<std::endl;
	std::cout<<"length  "<<length <<std::endl;
}
